package org.plr.ecommerce.view;

import org.plr.ecommerce.view.home.HomePage;
import java.util.Map;
import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.spring.SpringWebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.hibernate.SessionFactory;
import org.plr.ecommerce.view.catalog.CatalogPage;

public class Application extends SpringWebApplication {

    public static Application get() {
        return (Application) SpringWebApplication.get();
    }

    public Application() {
    }

    @Override
    public Class<HomePage> getHomePage() {
        return HomePage.class;
    }

    @Override
    protected void init() {
        addComponentInstantiationListener(new SpringComponentInjector(this));
        this.mountBookmarkablePage("catalog", CatalogPage.class);
    }

    @Override
    public RequestCycle newRequestCycle(Request request, Response response) {

        SessionFactory sessionFactory = getBean(SessionFactory.class);
        RequestCycle requestCycle = new RequestCycle(this, (WebRequest) request, response);
        requestCycle.setSessionFactory(sessionFactory);
        return requestCycle;
    }

    public <T> T getBean(Class<T> clazz) {
        T result = null;
        Map<String, T> beans = (Map<String, T>) this.internalGetApplicationContext().getBeansOfType(clazz);
        if (0 < beans.size()) {
            result = beans.values().iterator().next();
        }
        return result;
    }
}
